<template>
  <view
    class="page"
    :prop="Symbol"
    :change:prop="renderBiz.onChange"
    id="renderjs-view"
  >
    <template v-if="detail">
      <t-header @back="navBack">
        <view class="header ml-28">
          <image
            class=""
            :src="`/static/images/icons/${marketCode}.png`"
          ></image>
          <text>{{ detail['f58'] }}</text>
          <text>[{{ detail['f57'] }}]</text>
        </view>
        <template #right>
          <view class="flex align-center">
            <tui-icon
              @click="toShareSearch"
              color="white"
              name="search"
              :size="36"
            ></tui-icon>
          </view>
        </template>
      </t-header>

      <view class="container-wrap padding-sm">
        <view class="flex align-center">
          <view class="flex-1 block">
            <view
              class="text-xxl text-60px bold"
              :class="detail['f169'] > 0 ? 'text-red' : 'text-green'"
              >{{ friendText(detail['f43'] / 100) }}</view
            >
            <view
              class="flex t-24 space-between"
              :class="detail['f169'] > 0 ? 'text-red' : 'text-green'"
            >
              <view>
                {{
                  friendText(
                    detail['f169'] > 0
                      ? '+' + detail['f169'] / 100
                      : detail['f169'] / 100
                  )
                }}
              </view>
              <view>
                {{
                  friendText(
                    detail['f170'] > 0
                      ? '+' + detail['f170'] / 100
                      : detail['f170'] / 100
                  )
                }}%
              </view>
            </view>
            <view class="more-info">
              <view class="label">换手率</view>
              <view class="t-24">{{ friendText(detail['f168'] / 100) }}%</view>
            </view>
            <view class="more-info">
              <view class="label">市盈率</view>
              <view>{{ friendText(detail['f162'] / 100) }}%</view>
            </view>
          </view>
          <view class="flex-1 block ml-64">
            <view class="more-info">
              <view class="label">今开</view>
              <view>{{ friendText(detail['f46'] / 100) }}</view>
            </view>
            <view class="more-info">
              <view class="label">昨收</view>
              <view>{{ friendText(detail['f60'] / 100) }}</view>
            </view>
            <view class="more-info">
              <view class="label">日振幅</view>
              <view>{{ friendText(rizhenfu) }} %</view>
            </view>
            <view class="more-info">
              <view class="label">总市值</view>
              <view>{{ friendText(formatNumberUnit(detail['f116'])) }}</view>
            </view>
            <view class="more-info">
              <view class="label">流通市值</view>
              <view>{{ formatNumberUnit(detail['f117']) }}</view>
            </view>
          </view>

          <view class="flex-1 block ml-64">
            <view class="more-info">
              <view class="label">最低</view>
              <view>{{ friendText(detail['f45'] / 100) }}</view>
            </view>
            <view class="more-info">
              <view class="label">最高</view>
              <view>{{ friendText(detail['f44'] / 100) }}</view>
            </view>
            <view class="more-info">
              <view class="label">成交量</view>
              <view>{{ formatNumberUnit(detail['f47']) }}手</view>
            </view>
            <view class="more-info">
              <view class="label">成交额</view>
              <view>{{ friendText(formatNumberUnit(detail['f48'])) }}</view>
            </view>
            <view class="more-info">
              <view class="label">市净率</view>
              <view>{{ friendText(detail['f167'] / 100) }}%</view>
            </view>
          </view>
        </view>
        <!-- 0 日线 1 周线 2 月线 3 年线  -->
        <view
          class="flex align-center justify-between border-top padding-top-sm"
        >
          <text
            :class="tabIndex == 0 ? 'tab active-tab' : 'tab'"
            @click="ChangeChartType('minutetype')"
            >分时</text
          >
          <text
            :class="tabIndex == 1 ? 'tab active-tab' : 'tab'"
            @click="ChangeKLinePeriod(0)"
            >日K</text
          >
          <text
            :class="tabIndex == 2 ? 'tab active-tab' : 'tab'"
            @click="ChangeKLinePeriod(1)"
            >周K</text
          >
          <text
            :class="tabIndex == 3 ? 'tab active-tab' : 'tab'"
            @click="ChangeKLinePeriod(2)"
            >月K</text
          >
          <text
            :class="tabIndex == 4 ? 'tab active-tab' : 'tab'"
            @click="ChangeKLinePeriod(3)"
            class="padding-right-sm"
            >年</text
          >
          <tui-icon name="setup" :size="22"></tui-icon>
        </view>
        <view class="flex margin-top-sm">
          <view class="flex-sub">
            <HQChartControl
              ref="HQChartCtrl"
              :DefaultChart="{ Type: 'KLine' }"
              :DefaultSymbol="Symbol"
            >
            </HQChartControl>
          </view>

          <view class="col-3 flex-grow-0">
            <view class="bg-white">
              <view
                class="padding-xs flex align-center text-sm"
                v-for="(item, index) in sell5"
                :key="index"
              >
                <text>卖{{ index + 1 }}</text>
                <text class="flex-sub text-green padding-left-xs">{{
                  item.price
                }}</text>
                <text class="text-green">{{ item.num }}</text>
              </view>
            </view>
            <view class="border-top bg-white">
              <view
                class="padding-xs flex align-center text-sm"
                v-for="(item, index) in buy5"
                :key="index"
              >
                <text>买{{ index + 1 }}</text>
                <text class="flex-sub text-red padding-left-xs">{{
                  item.price
                }}</text>
                <text class="text-red">{{ item.num }}</text>
              </view>
            </view>
            <view class="flex justify-between text-sm text-bold">
              <view>五档</view>
              <view>明细</view>
            </view>
          </view>
        </view>
      </view>

      <view class="tit">今日资金</view>

      <view class="container-wrap padding-sm">
        <view style="padding: 0 60rpx">
          <qiun-data-charts type="rose" :opts="opts" :chartData="chartData" />
        </view>
        <view class="flex">
          <view class="col-2 padding-left">流入</view>
          <view class="col-2 padding-left">流出</view>
        </view>
        <view class="flex flex-wrap" v-if="chartData.series">
          <view
            class="chart-tip"
            v-for="(item, index) in capitalInOut"
            :key="index"
          >
            <view class="rect" :style="{ background: item.color }"></view>
            <view class="flex-sub">{{ item.name }}</view>
            <view>{{ formatNumberUnit(item.value) }}</view>
          </view>
        </view>

        <view class="flex margin-top">
          <view class="col-3 padding-left text-sm flex-grow-0">
            <view>
              <text>流入</text>
              <text class="padding-left text-red">{{
                formatNumberUnit(totalMoney['in'])
              }}</text>
            </view>
            <view class="padding-top-sm">
              <text>流出</text>
              <text class="padding-left text-green">{{
                formatNumberUnit(totalMoney['out'])
              }}</text>
            </view>
            <view class="padding-top-sm">
              <text>净值</text>
              <text
                class="padding-left"
                :class="totalMoney['abs'] > 0 ? 'text-red' : 'text-green'"
                >{{ formatNumberUnit(totalMoney['abs']) }}</text
              >
            </view>
          </view>
          <view class="flex-sub rel" style="width: 416rpx; height: 200rpx">
            <qiun-data-charts
              type="column"
              :opts="columOpt"
              :chartData="columData"
            />
          </view>
        </view>
      </view>

      <view style="height: 140rpx"></view>
      <view class="pos-b">
        <view class="text-center" @click="createOrder(0)">
          <image src="../../static/images/icons/icon_buy.png" mode=""></image>
          <view>买入</view>
        </view>
        <view class="text-center" @click="createOrder(1)">
          <image src="../../static/images/icons/icon_sell.png" mode=""></image>
          <view>卖出</view>
        </view>

        <view v-if="is_rq == 1" class="text-center" @click="createOrder_r(0)">
          <image src="../../static/images/icons/rbuy.png" mode=""></image>
          <view>融买</view>
        </view>
        <view v-if="is_rq == 1" class="text-center" @click="createOrder_r(1)">
          <image src="../../static/images/icons/rsell.png" mode=""></image>
          <view>融卖</view>
        </view>
        <view class="text-center" @click="addzx">
          <image
            style="width: 45rpx"
            :src="`/static/images/icons/icon_${
              is_zx == 1 ? 'delete' : 'add'
            }_fov.png`"
            mode=""
          ></image>
          <view>{{ is_zx == 1 ? '删除' : '自选' }}</view>
        </view>
      </view>
    </template>
  </view>
</template>

<script module="renderBiz" lang="renderjs">
  import renderBiz from './rederEventSource.js';
  export default {
  	mixins: [renderBiz]
  }
</script>

<script>
  import { getDotCode, getMarketCode, isExchangTime } from '@/utils/stock.js';
  import { addzx, stockDetail, delzx } from '@/api/index.js';
  import HQChartControl from '@/uni_modules/jones-hqchart2/js_sdk/HQChartControl.vue';
  import { rigOpt, columOpt, DefaultData, NetworkFilter } from './chartOpt.js';
  import utils from '@/components/common/tui-utils/tui-utils';
  import tui from '@/common/httpRequest.js';
  import THeader from '@/components/views/t-header/index.vue';
  function formatNum(num) {
    if (typeof num != 'number') return num;
    return (num / 100).toFixed(2);
  }
  export default {
    components: {
      HQChartControl,
      THeader,
    },
    data() {
      return {
        tabIndex: 0,
        isShowMinuteChart: true,
        Symbol: '603999.sh',
        marketCode: 'sh',
        chartData: {},
        opts: rigOpt,
        columOpt: columOpt,
        columData: {},
        sell5: [
          {
            price: '--',
            num: '--',
          },
          {
            price: '--',
            num: '--',
          },
          {
            price: '--',
            num: '--',
          },
          {
            price: '--',
            num: '--',
          },
          {
            price: '--',
            num: '--',
          },
        ],
        buy5: [
          {
            price: '--',
            num: '--',
          },
          {
            price: '--',
            num: '--',
          },
          {
            price: '--',
            num: '--',
          },
          {
            price: '--',
            num: '--',
          },
          {
            price: '--',
            num: '--',
          },
        ],
        detail: null,
        is_zx: 0,
        is_rq: 0,
        capitalInOut: [], //资金流入流出
        rizhenfu: '--', //日震幅
        totalMoney: {
          //总计资金
          in: 0, //总流入
          out: 0, //总流出
          abs: 0, //净值
        },
      };
    },
    onLoad(t) {
      if (t.code && t.code != 'undefined') {
        this.Symbol = getDotCode(t.code);
        this.marketCode = getMarketCode(t.code);
        this.getDetail();
      }

      this.updataUchart = utils.throttle(this.upUchart, 10000, 1); //节流避免uchart频繁更新
      this.first = true; //是否第一次】
    },
    onShow() {
      if (this.detail) {
        //重连
        let temp = this.Symbol;
        this.Symbol = 'null';
        setTimeout(() => {
          this.Symbol = temp;
        }, 10);
      }
    },
    onReady() {
      // this.getMsgPush()
    },
    onUnload() {
      try {
        // 主动销毁节省性能
        // this.$store.commit('destoryEventSource')
        this.Symbol = 'null';
        let hqchartCtrl = this.$refs.HQChartCtrl;
        hqchartCtrl.GetJSChart().ChartDestory();
      } catch (err) {
        console.log(err);
        //TODO handle the exception
      }
    },
    methods: {
      friendText: function (value) {
        if (!value || value == 'NaN' || value == 'undefined' || value == NaN) {
          return '--';
        }
        return value;
      },
      navBack() {
        this.Symbol = 'null';
        uni.navigateBack();
      },
      getDetail() {
        let allcode = this.Symbol.split('.');
        stockDetail({
          q: allcode[1] + allcode[0],
        }).then((res) => {
          this.is_zx = res.data.is_zx;
          this.is_rq = res.data.is_rq;
        });
      },
      addzx() {
        console.log(2222222, tui);

        let allcode = this.Symbol.split('.');
        let Fn = addzx;
        if (this.is_zx == 1) {
          Fn = delzx;
        }
        Fn({
          allcode: allcode[1] + allcode[0],
          code: allcode[0],
        }).then((res) => {
          tui.toast(res.msg);
          this.getDetail();
        });
      },
      formatNumberUnit(num) {
        if (num < 1e4) return num; // 小于1万直接返回原数字
        if (num >= 1e4 && num < 1e8) return +(num / 1e4).toFixed(2) + '万'; // 大于等于1万小于1亿的数字转换成万
        if (num >= 1e8 && num < 1e12) return +(num / 1e8).toFixed(2) + '亿'; // 大于等于1亿小于1万亿的数字转换成亿
        if (num >= 1e12) return +(num / 1e12).toFixed(2) + '万亿'; // 大于等于1万亿的数字转换成万亿
      },
      acceptDataFromRenderjs(data) {
        // console.log(data);
        this.actionData(data);
      },
      actionData(data) {
        let needUpdataUchart = false; //是否需要更新呢统计图表
        if (data) {
          for (let key in data) {
            //流入流出资金
            let keyNum = key.match(/\d+(\.\d+)?/g)[0];
            if (keyNum >= 137 && keyNum <= 149) {
              needUpdataUchart = true;
            }

            console.log(111111111, key);

            if (!this.first) {
              this.detail[key] = data[key];
            }
          }

          if (this.first) {
            this.detail = data;
            this.$nextTick(() => {
              this.CreateHQChart();
            });
          }
          if (needUpdataUchart) {
            this.$nextTick(() => {
              this.updataUchart();
            });
          }
          this.first = false;
          let sell5Key = [
            ['f31', 'f32'],
            ['f33', 'f34'],
            ['f35', 'f36'],
            ['f37', 'f38'],
            ['f39', 'f40'],
          ];
          sell5Key.forEach((item, index) => {
            this.sell5[index].price = data[item[0]]
              ? formatNum(data[item[0]])
              : this.sell5[index].price;
            this.sell5[index].num = data[item[1]]
              ? data[item[1]]
              : this.sell5[index].num;
          });
          let buy5Key = [
            ['f19', 'f20'],
            ['f17', 'f18'],
            ['f15', 'f16'],
            ['f13', 'f14'],
            ['f11', 'f12'],
          ];
          buy5Key.forEach((item, index) => {
            this.buy5[index].price = data[item[0]]
              ? formatNum(data[item[0]])
              : this.buy5[index].price;
            this.buy5[index].num = data[item[1]]
              ? data[item[1]]
              : this.buy5[index].num;
          });
          this.rizhenfu = (
            (Math.abs(this.detail['f45'] - this.detail['f44']) * 100) /
            this.detail['f60']
          ).toFixed(2);
        }
      },
      getMsgPush() {
        this.$store.dispatch('creartEventSource', {
          symbol: this.Symbol,
          onMsg: (data) => {
            this.actionData(data);
          },
        });
      },
      async createOrder(i) {
        let isExchang = await isExchangTime();
        console.log(isExchang);

        if (isExchang) {
          uni.navigateTo({
            url: './creatOrder?type=' + i + '&code=' + this.Symbol,
          });
        } else {
          tui.toast('不在交易时间段');
        }
      },
      async createOrder_r(i) {
        let isExchang = await isExchangTime();
        console.log(isExchang);

        if (isExchang) {
          uni.navigateTo({
            url: './creatOrder-r?type=' + i + '&code=' + this.Symbol,
          });
        } else {
          tui.toast('不在交易时间段');
        }
      },
      ChangeKLinePeriod(period) {
        this.tabIndex = period + 1;
        let hqchartCtrl = this.$refs.HQChartCtrl;
        hqchartCtrl.ChangeKLinePeriod(period);
      },
      ClearHQChart() {
        let hqchartCtrl = this.$refs.HQChartCtrl;
        if (hqchartCtrl) hqchartCtrl.ClearChart();
      },
      ChangeChartType(type) {
        this.tabIndex = 0;
        let hqchartCtrl = this.$refs.HQChartCtrl;
        switch (type) {
          case 'minutetype':
            this.isShowMinuteChart = true;
            if (hqchartCtrl.IsMinuteChart()) return;

            break;
          case 'klinetype':
            this.isShowMinuteChart = false;
            if (hqchartCtrl.IsKLineChart()) return;

            break;
        }

        this.$nextTick(() => {
          this.ClearHQChart();
          this.$nextTick(() => {
            this.CreateHQChart();
          });
        });
      },
      upUchart() {
        function getVal(val) {
          if (val == '-') return 0;
          return val;
        }

        let res = {
          series: [
            {
              data: [
                {
                  name: '大单买入',
                  value: getVal(this.detail['f141']),
                },
                {
                  name: '中单买入',
                  value: getVal(this.detail['f144']),
                },
                {
                  name: '小单买入',
                  value: getVal(this.detail['f147']),
                },
                {
                  name: '大单卖出',
                  value: getVal(this.detail['f142']),
                },
                {
                  name: '中单卖出',
                  value: getVal(this.detail['f145']),
                },
                {
                  name: '小单卖出',
                  value: getVal(this.detail['f148']),
                },
              ],
            },
          ],
        };

        this.capitalInOut = [
          {
            name: '大单买入',
            value: getVal(this.detail['f141']),
            color: '#EE5562',
          },
          {
            name: '大单卖出',
            value: getVal(this.detail['f142']),
            color: '#2472C7',
          },
          {
            name: '中单买入',
            value: getVal(this.detail['f144']),
            color: '#F16934',
          },
          {
            name: '中单卖出',
            value: getVal(this.detail['f145']),
            color: '#59B664',
          },
          {
            name: '小单买入',
            value: getVal(this.detail['f147']),
            color: '#F19B34',
          },
          {
            name: '小单卖出',
            value: getVal(this.detail['f148']),
            color: '#97C962',
          },
        ];
        this.chartData = JSON.parse(JSON.stringify(res));

        let totalMoney = {
          in: getVal(this.detail['f138']),
          out: getVal(this.detail['f139']),
        };
        totalMoney.abs = totalMoney.in - totalMoney.out;
        this.totalMoney = totalMoney;

        let arr = [
          getVal(this.detail['f143']),
          getVal(this.detail['f146']),
          getVal(this.detail['f149']),
        ];
        this.columOpt.yAxis.data = [
          {
            min: Math.min.apply(arr),
            min: Math.max.apply(arr),
          },
        ];
        let ret = {
          categories: ['大单', '中单', '小单'],
          series: [
            {
              name: '值',
              data: [
                {
                  color: '#59B664',
                  value: getVal(this.detail['f143']),
                },
                {
                  color: '#EE5562',
                  value: getVal(this.detail['f146']),
                },
                {
                  color: '#F19B34',
                  value: getVal(this.detail['f149']),
                },
              ],
            },
          ],
        };
        this.columData = JSON.parse(JSON.stringify(ret));
      },
      CreateHQChart() {
        let hqchartCtrl = this.$refs.HQChartCtrl;
        if (this.isShowMinuteChart) {
          hqchartCtrl.ChartType = 'Minute';
          hqchartCtrl.Minute.Option = DefaultData.GetMinuteOption();
        } else {
          hqchartCtrl.ChartType = 'KLine';
          hqchartCtrl.KLine.Option = DefaultData.GetKLineOption();
        }

        hqchartCtrl.NetworkFilter = NetworkFilter;
        hqchartCtrl.SetSize(uni.upx2px(223 * 2), uni.upx2px(261 * 2));
        hqchartCtrl.OnSize();
        hqchartCtrl.CreateHQChart();
      },

      toShareSearch() {
        uni.navigateTo({
          url: '/pages/search/index',
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .headf {
    padding: 0 1.2rem;
    height: 4rem;
    position: relative;
    // width: 100%;
    z-index: 33;
    background-color: #f5f5f5;
  }
  .header {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: flex-start;
    font-size: 36rpx;
    color: white;
    line-height: 36rpx;

    image {
      width: 36rpx;
      height: 36rpx;
      margin-right: 6rpx;
    }
  }

  .container-wrap {
    border-radius: 34rpx;
    background: #fff;
    margin: 18rpx;
    overflow: hidden;
  }

  .more-info {
    width: 100%;
    padding: 10rpx 6rpx;
    box-sizing: border-box;
    font-size: 24rpx;
    line-height: 28rpx;
    display: flex;
    justify-content: space-between;

    .label {
      color: #535353;
    }
  }

  .tit {
    margin: 20rpx;
    font-weight: bold;
  }

  .chart-tip {
    width: 50%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 0 0 30rpx;
    box-sizing: border-box;
    font-size: 20rpx;

    .circle {
      width: 16rpx;
      height: 16rpx;
      border-radius: 50%;
      margin-right: 6rpx;
    }
    .rect {
      width: 12rpx;
      height: 12rpx;
      margin-right: 8rpx;
    }
  }

  .col-2 {
    box-sizing: border-box;
  }

  .pos-b {
    position: fixed;
    bottom: 0;
    display: flex;
    align-items: center;
    padding: 20rpx;
    left: 0;
    width: 100%;
    background: #fff;
    box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.2);
    justify-content: space-around;

    image {
      width: 52rpx;
      height: 52rpx;
    }
  }

  .text-60px {
    font-size: 60rpx;
  }

  .bold {
    font-weight: bold;
  }
  .flex-1 {
    flex: 1;
  }
  .t-24 {
    font-size: 24rpx;
    line-height: 28rpx;
  }
  .space-between {
    justify-content: space-between;
  }
  .ml-64 {
    margin-left: 34rpx;
  }
  .block {
  }
  .active-tab {
    color: #f13444;
    &::after {
      background-color: #f13444;
    }
  }
  .tab {
    text-align: center;
    display: flex;
    align-items: center;
    flex-direction: column;
    font-size: 24rpx;

    line-height: 34rpx;
    &::after {
      content: '';
      display: block;
      width: 24rpx;
      height: 4rpx;
    }
  }
  .ml-28 {
    margin-left: 28rpx;
  }
  // @media (prefers-color-scheme: dark) {
  // 	.container-wrap{background:#111111 !important;}
  // 	.pos-b{background:#111111 !important;}
  // }
</style>
